import {useState} from 'react';
import './style.css'

function Square({value, onSquareClick}) {
    // const [value, setValue] = useState(null);
    //
    // function handlerClick() {
    //     setValue('x')
    // }

    return (<button className="square" onClick={onSquareClick}>{value}</button>)
}

export default function
    () {
    const [xIsNext, setXIsNext] = useState(true);
    const [squares, setSquares] = useState(Array(9).fill(null));
    // const winner = calculateWinner(squares);
    // let status;
    // if (winner) {
    //     status = "winner: " + winner
    // } else {
    //     console.log("111111111")
    //     status = "next player: " + (xIsNext ? 'x' : 'O')
    // }


    const [status, setStatus] = useState('开始');


    function handlerClick(i) {
        /** 为什么每次判断输赢，不是写在点击事件 **/
        const winner = calculateWinner(squares);
        if (winner) {
            setStatus("winner: " + winner)
        } else {
            setStatus("next player: " + (xIsNext ? 'x' : 'O'))
        }

        if (squares[i] || calculateWinner(squares)) {
            return;
        }

        const nextSquares = squares.slice();
        if (xIsNext) {
            nextSquares[i] = "X";
        } else {
            nextSquares[i] = "O";
        }
        setSquares(nextSquares);
        setXIsNext(!xIsNext)
    }

    return (
        <>
            <div className="status">{status}</div>
            <div className="board-row">
                <Square value={squares[0]} onSquareClick={() => handlerClick(0)}></Square>
                <Square value={squares[1]} onSquareClick={() => handlerClick(1)}></Square>
                <Square value={squares[2]} onSquareClick={() => handlerClick(2)}></Square>
            </div>
            <div className="board-row">
                <Square value={squares[3]} onSquareClick={() => handlerClick(3)}></Square>
                <Square value={squares[4]} onSquareClick={() => handlerClick(4)}></Square>
                <Square value={squares[5]} onSquareClick={() => handlerClick(5)}></Square>
            </div>
            <div className="board-row">
                <Square value={squares[6]} onSquareClick={() => handlerClick(6)}></Square>
                <Square value={squares[7]} onSquareClick={() => handlerClick(7)}></Square>
                <Square value={squares[8]} onSquareClick={() => handlerClick(8)}></Square>
            </div>
        </>
    );
}

function calculateWinner(squares) {
    const lines = [
        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8],
        [0, 3, 6],
        [1, 4, 7],
        [2, 5, 8],
        [0, 4, 8],
        [2, 4, 6]
    ];
    for (let i = 0; i < lines.length; i++) {
        const [a, b, c] = lines[i];
        if (squares[a] && squares[a] === squares[b] && squares[b] === squares[c]) {
            return squares[a];
        }
    }
    return null;
}

